package com.goatrock.media.thisway.domain.adapter.impl;

import com.goatrock.media.thisway.common.constants.ApplicationConstants;
import com.goatrock.media.thisway.common.exceptions.ServiceException;
import com.goatrock.media.thisway.common.util.FileHandlers;
import com.goatrock.media.thisway.domain.adapter.InitializeAppServiceAdapter;
import java.io.File;
import org.apache.log4j.Logger;

public class InitializeAppServiceAdapterImpl implements InitializeAppServiceAdapter{
    private static Logger logger = Logger.getLogger(InitializeAppServiceAdapterImpl.class);

    public void InitializeAppComponentsAndDependecies() throws ServiceException {
        logger.debug("Inside the InitAppServiceAdapter");

        boolean success = true;
        if(!(new File(ApplicationConstants.DEFAULT_SCRIPT_LOCATION).exists())){
            logger.debug("App/Script folder was NOT found. Attempting to create one at this location:"+ApplicationConstants.DEFAULT_SCRIPT_LOCATION);
//            SecurityManager sm = new SecurityManager();
//            try{
//                sm.checkWrite(ApplicationConstants.DEFAULT_SCRIPT_LOCATION);
//            }catch(SecurityException se){
//                logger.error("Security Exception:"+se.getMessage());
//            }

            success = (new File(ApplicationConstants.DEFAULT_SCRIPT_LOCATION).mkdirs());


        }

        if(success){
            if(!(new File(ApplicationConstants.DEFAULT_SCRIPT_LOCATION+"\\"+ApplicationConstants.VBSCRIPT_CREATE_SHORTCUT_FILE_NAME).exists())){
                logger.debug(ApplicationConstants.VBSCRIPT_CREATE_SHORTCUT_FILE_NAME+" file was not found.  Attempting to create it.");
                success = FileHandlers.copyFile(FileHandlers.retrieveClasspathResource("..\\ThisWay-Domain\\src\\main\\resources\\"+ApplicationConstants.VBSCRIPT_CREATE_SHORTCUT_FILE_NAME),new File(ApplicationConstants.DEFAULT_SCRIPT_LOCATION+"\\"+ApplicationConstants.VBSCRIPT_CREATE_SHORTCUT_FILE_NAME));
            }
            if(!(new File(ApplicationConstants.DEFAULT_SCRIPT_LOCATION+"\\"+ApplicationConstants.VBSCRIPT_REMOVE_FOLDER_FILE_NAME).exists())){
                logger.debug(ApplicationConstants.VBSCRIPT_REMOVE_FOLDER_FILE_NAME+" file was not found.  Attempting to create it.");
                success = FileHandlers.copyFile(FileHandlers.retrieveClasspathResource("..\\ThisWay-Domain\\src\\main\\resources\\"+ApplicationConstants.VBSCRIPT_REMOVE_FOLDER_FILE_NAME),new File(ApplicationConstants.DEFAULT_SCRIPT_LOCATION+"\\"+ApplicationConstants.VBSCRIPT_REMOVE_FOLDER_FILE_NAME));
            }
        }else{
            logger.error("An error occured trying to create the App/Script folder");
            throw new ServiceException("FOLDER_CREATION","Folder was not able to be created:"+ApplicationConstants.DEFAULT_SCRIPT_LOCATION);
        }
    }

    
}
